import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Table, Spin, Toast, Button, Popconfirm, Space, Input, DatePicker, Select } from '@douyinfe/semi-ui';
import axiosInstance from './axiosInstance';

interface User {
  id: string;
  phone: string;
  status: number;
  channelId: number;
  createTime: string;
}

const UserList: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchText, setSearchText] = useState('');
  const [searchType, setSearchType] = useState<'phone' | 'id'>('phone');
  const [dateRange, setDateRange] = useState<[Date, Date] | null>(null);

  // 使用React Router的useParams hook获取路径参数
  const { channelId } = useParams();
  const navigate = useNavigate();

  /**
   * 删除用户
   * @param id 用户ID
   */
  const handleDelete = async (id: string) => {
    try {
      const response = await fetch('/lowcode3user/user/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          id,
          channelId 
        }),
      });

      const result = await response.json();
      if (result.errorCode === '0') {
        Toast.success('删除成功');
        fetchUsers(); // 重新加载用户列表
      } else {
        Toast.error(result.errorMessage || '删除失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      Toast.error('删除失败');
    }
  };

  /**
   * 处理用户编辑操作
   * @param userId 用户ID
   */
  const handleEdit = (userId: string) => {
    navigate(`/${channelId}/users/edit/${userId}`);
  };

  /**
   * 获取用户列表数据
   */
  const fetchUsers = async () => {
    setLoading(true);
    
    if (!channelId) {
      setError('缺少channelId参数');
      setLoading(false);
      return;
    }

    try {
      const res = await axiosInstance.post('/lowcode3user/user/findAllByChannelId', {
        channelId: parseInt(channelId, 10)
      });
      
      // 根据实际API响应结构处理数据
      if (res.data.errorCode === '0') {
        const userData = res.data.data || [];
        setUsers(userData);
        setFilteredUsers(userData);
        setError(null);
      } else {
        setError(res.data.value || '加载失败');
      }
    } catch (err: any) {
      setError(err.message || '加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [channelId]);

  /**
   * 搜索和筛选用户
   * @param searchValue 搜索关键词
   * @param searchField 搜索字段类型
   * @param dateFilter 日期筛选范围
   */
  const handleFilter = (searchValue: string, searchField: 'phone' | 'id', dateFilter: [Date, Date] | null) => {
    let filtered = users;
    
    // 文本搜索筛选 - 根据搜索类型进行精确字段搜索
    if (searchValue.trim()) {
      filtered = filtered.filter(user => {
        const fieldValue = searchField === 'phone' ? user.phone : user.id;
        return fieldValue.toLowerCase().includes(searchValue.toLowerCase());
      });
    }
    
    // 日期范围筛选
    if (dateFilter && dateFilter[0] && dateFilter[1]) {
      const [startDate, endDate] = dateFilter;
      filtered = filtered.filter(user => {
        const createTime = new Date(user.createTime);
        return createTime >= startDate && createTime <= endDate;
      });
    }
    
    setFilteredUsers(filtered);
  };

  /**
   * 处理搜索文本变化
   * @param value 搜索文本
   */
  const handleSearchChange = (value: string) => {
    setSearchText(value);
    handleFilter(value, searchType, dateRange);
  };

  /**
   * 处理搜索类型变化
   * @param type 搜索类型
   */
  const handleSearchTypeChange = (type: 'phone' | 'id') => {
    setSearchType(type);
    // 搜索类型变化时，如果有搜索文本，重新执行搜索
    if (searchText.trim()) {
      handleFilter(searchText, type, dateRange);
    }
  };

  /**
   * 处理日期范围变化
   * @param dates 日期范围
   */
  const handleDateRangeChange = (dates: [Date, Date] | null) => {
    setDateRange(dates);
    handleFilter(searchText, searchType, dates);
  };

  // 监听用户数据变化，重新应用筛选
  useEffect(() => {
    handleFilter(searchText, searchType, dateRange);
  }, [users]);

  if (loading) return <Spin size="large" />;
  if (error) {
    Toast.error(error);
    return <div>加载失败: {error}</div>;
  }


  return (
    <div>
      {/* 表格头部操作区域 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: 16 
      }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          {/* 搜索类型选择器 */}
          <Select
            value={searchType}
            onChange={handleSearchTypeChange}
            style={{ width: 120 }}
            optionList={[
              { value: 'phone', label: '手机号' },
              { value: 'id', label: '用户编号' }
            ]}

          />
          {/* 搜索框 */}
          <Input
            placeholder={searchType === 'phone' ? '搜索手机号' : '搜索用户编号'}
            value={searchText}
            onChange={handleSearchChange}
            style={{ width: 280 }}
            prefix={<span>🔍</span>}
            showClear
          />
          {/* 注册时间筛选 */}
          <DatePicker
            type="dateRange"
            placeholder={['开始日期', '结束日期']}
            value={dateRange}
            onChange={handleDateRangeChange}
            style={{ width: 280 }}
            format="yyyy-MM-dd"
          />
        </div>
        <div>
          {/* 右侧操作区域 - 添加用户按钮 */}
          <Button 
            type="primary" 
            onClick={() => navigate(`/${channelId}/users/create`)}
            style={{ marginLeft: 8 }}
          >
            添加用户
          </Button>
        </div>
      </div>
      
      {/* 表格主体 */}
      <Table
        columns={[
          { title: 'ID', dataIndex: 'id', key: 'id' },
          { title: '手机号', dataIndex: 'phone', key: 'phone' },
          { 
            title: '状态', 
            dataIndex: 'status', 
            key: 'status',
            render: (status: number) => status === 1 ? '启用' : '禁用'
          },
          { title: '渠道ID', dataIndex: 'channelId', key: 'channelId' },
          { 
            title: '创建时间', 
            dataIndex: 'createTime', 
            key: 'createTime',
            render: (time: string) => new Date(time).toLocaleString('zh-CN')
          },
          {
            title: '操作',
            key: 'action',
            render: (text: any, record: User) => (
              <Space>
                <Button 
                  type="primary" 
                  size="small"
                  onClick={() => handleEdit(record.id)}
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个用户吗？"
                  content="删除后无法恢复"
                  onConfirm={() => handleDelete(record.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    type="danger" 
                    size="small"
                  >
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
        dataSource={filteredUsers}
        rowKey="id"
        pagination={false}
      />
    </div>
  );
};

export default UserList;